import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';
import 'package:flutter_swiper/flutter_swiper.dart'; // 录播图组件
import 'package:flutter_trip/dao/home_dao.dart'; // 接口文件
import 'package:flutter_trip/model/common_model.dart';
import 'package:flutter_trip/model/grid_nav_model.dart';
import 'package:flutter_trip/model/home_model.dart';
import 'package:flutter_trip/model/sale_box_model.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/pages/speak.dart';
import 'package:flutter_trip/util/navigator_util.dart';
import 'package:flutter_trip/widget/grid_nav.dart'; // 网格组件
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/local_nav.dart'; // 本地导航
import 'package:flutter_trip/widget/sales_box.dart'; // 活动
import 'package:flutter_trip/widget/search_bar.dart';
import 'package:flutter_trip/widget/sub_nav.dart';
import 'package:flutter_trip/widget/webview.dart'; // 子nav

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  List<CommonModel> bannerList = [];
  // appBar 透明度
  double _appBarAlpha = 0;
  bool _isLoading = true; //是否加载

  String resultString = '';
  // localNavList
  List<CommonModel> localNavList = [];
  GridNavModel gridNavModel;
  List<CommonModel> subNavList = [];
  SalesBoxModel salesBox;

  // 页面滚动回调
  _onScroll(offset) {
    double alpha = offset / 150;

    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      _appBarAlpha = alpha;
    });
    print(_appBarAlpha);
  }

  // 加载/调用数据方法
  Future<Null> _handleRefresh() async {
    // 调用home dao
    // HomeDao.fetch().then((value) {
    //
    // }).catchError((e) {
    //   setState(() {
    //     resultString = json.encode(e);
    //   });
    // });

    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        // resultString = json.encode(model);
        localNavList = model.localNavList;
        gridNavModel = model.gridNav;
        subNavList = model.subNavList;
        salesBox = model.salesBox;
        bannerList = model.bannerList;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        resultString = json.encode(e);
        _isLoading = false;
      });
    }

    return null;
  }

  //
  @override
  void initState() {
    super.initState();
    _handleRefresh();
    Future.delayed(Duration(milliseconds: 600), () {
      FlutterSplashScreen.hide(); // 关闭启动屏});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff2f2fa),
      body: LoadingContain(
        isLoading: _isLoading,
        cover: true,
        child: Stack(
          children: [
            // 移除padding
            MediaQuery.removePadding(
                removeTop: true,
                context: context,
                // 监听组件滚动
                child: _refreshIndicator),
            _appBar
          ],
        ),
      ),
    );
  }

  // 刷新加载
  Widget get _refreshIndicator {
    return RefreshIndicator(
        displacement: 80,
        child: NotificationListener(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollUpdateNotification &&
                  scrollNotification.depth == 0) {
                // 滚动且是列表滚动的时候
                _onScroll(scrollNotification.metrics.pixels);
              }
            },
            child: _listView),
        onRefresh: _handleRefresh);
  }

  // home页面列表
  Widget get _listView {
    return ListView(
      children: [
        Container(height: 160, child: _swiper),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GridNav(
            gridNavModel: gridNavModel,
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(
            subNavList: subNavList,
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SalesBox(
            salesBox: salesBox,
          ),
        ),
      ],
    );
  }

  //swiper
  Widget get _swiper {
    return Swiper(
      itemCount: bannerList.length,
      autoplay: true,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {
            NavigatorUtil.push(
                context,
                WebView(
                  url: bannerList[index].url,
                  title: bannerList[index].title,
                ));
          },
          child: Image.network(
            bannerList[index].icon,
            fit: BoxFit.fill,
          ),
        );
      },
      pagination: SwiperPagination(),
    );
  }

  // home页面appbar
  Widget get _appBar {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0x6600000), Colors.transparent],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
                color: Color.fromARGB(
                    (_appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: SearchBar(
              searchBarType: _appBarAlpha > 0.2
                  ? SearchBarType.homeLigh
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _juampToSpeak,
              defaultText: '发现更多新鲜事',
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: _appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
            boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)],
          ),
        )
      ],
    );
  }

  // 跳到搜索页面
  _jumpToSearch() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return SearchPage(hint: '口袋精灵');
    }));
  }

  // 跳到语音搜索页面
  _juampToSpeak() {
    NavigatorUtil.push(context, SpeakPage());
  }

  // 重新AutomaticKeepAliveClientMixin 的方法
  @override
  bool get wantKeepAlive => true;
}
